package com.jj.aop;

import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.util.ReflectionUtils;

@Slf4j
public class ProxyFactoryDemo {

    public static void main(String[] args) throws Exception {
//        ProxyFactory proxyFactory = new ProxyFactory();
//        proxyFactory.setTarget(new DummyImpl());
        ProxyFactory proxyFactory = new ProxyFactory(new DummyImpl());
//        proxyFactory.setOptimize(true);
        proxyFactory.setExposeProxy(false);
        proxyFactory.addAdvice(
                new MyInterceptor()
        );

        Dummy dummyProxy = (Dummy) proxyFactory.getProxy();
        dummyProxy.hello("test");
        log.debug("is aop proxy:{}", AopUtils.isAopProxy(dummyProxy));
        log.debug("is cglib proxy:{}", AopUtils.isCglibProxy(dummyProxy));
        log.debug("is jdk dynamic proxy:{}", AopUtils.isJdkDynamicProxy(dummyProxy));
        log.debug("target:{}", ((Advised) dummyProxy).getTargetSource().getTarget());
    }

    public static class MyInterceptor implements MethodInterceptor{

        @Override
        public Object invoke(MethodInvocation invocation) {
            log.debug("call {}", invocation.getMethod());
            return ReflectionUtils.invokeMethod(invocation.getMethod(),
                    invocation.getThis(), invocation.getArguments());
        }
    }
}
